<template>
  <div class="register-container">
    <form class="register-form" @submit.prevent="handleSubmit">
      <h2>注册</h2>
      <div class="form-group">
        <label for="username">用户名</label>
        <input 
          id="username"
          v-model="form.username" 
          type="text" 
          required 
          placeholder="请输入用户名"
        />
      </div>
      <div class="form-group">
        <label for="email">邮箱</label>
        <input 
          id="email"
          v-model="form.email" 
          type="email" 
          required 
          placeholder="请输入邮箱"
        />
      </div>
      <div class="form-group">
        <label for="password">密码</label>
        <input 
          id="password"
          v-model="form.password" 
          type="password" 
          required 
          placeholder="请输入密码"
        />
      </div>
      <div class="form-group">
        <label for="confirmPassword">确认密码</label>
        <input 
          id="confirmPassword"
          v-model="form.confirmPassword" 
          type="password" 
          required 
          placeholder="请再次输入密码"
        />
      </div>
      <button type="submit" class="btn-primary" :disabled="isSubmitting">
        {{ isSubmitting ? '注册中...' : '注册' }}
      </button>
      <button type="button" class="btn-link" @click="goLogin">
        已有账号？立即登录
      </button>
    </form>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import type { RegisterForm } from './types'
import { register } from './service'

const router = useRouter()
const form = ref<RegisterForm>({
  username: '',
  email: '',
  password: '',
  confirmPassword: ''
})
const isSubmitting = ref(false)

const handleSubmit = async () => {
  if (!form.value.username || !form.value.email || !form.value.password || !form.value.confirmPassword) {
    alert('请填写所有字段')
    return
  }

  if (form.value.password !== form.value.confirmPassword) {
    alert('两次输入的密码不一致')
    return
  }

  try {
    isSubmitting.value = true
    await register(form.value)
    alert('注册成功！请登录')
    router.push('/login')
  } catch (error) {
    alert('注册失败：' + (error instanceof Error ? error.message : '未知错误'))
  } finally {
    isSubmitting.value = false
  }
}

const goLogin = () => {
  router.push('/login')
}
</script>

<style scoped>
@import './style.css';
</style> 